import React, { memo, Component } from 'react'
import {
  Image,
  Avatar,
  Button,
  Input,
  InputNumber,
  Select,
  Alert,
  Modal,
  Upload,
  message
} from 'antd'
import { StudentInfo } from '../../utils/model'
import './index.css'
import { baseUrl } from '../../assets/baseUrl'
import {
  getUserInfo,
  getSchoollist,
  getClasslist,
  setMyBasicInfo
} from '@/api/user'
import { PlusOutlined } from '@ant-design/icons'
import { bindEmail, fixKey, sendCode, verifyEmail } from '@/api/index'
const BaseUrl = baseUrl()
const { Option } = Select
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
class setMybasicInfo extends Component {
  constructor(props) {
    super(props)
    this.state = {
      userInfo: null, //用户信息
      editing: false, //编辑状态
      schoolList: [], //学校列表
      classList: [], //班级列表
      fileList: [],
      firstChoose: false, //是否是第一次修改，根据是否有classId判定
      QQnumber: null, //QQ号
      classInfo: null, // 班级信息
      realName: null, //实名
      isButton: false, //邮箱按钮切换
      isOpen: false, //修改邮箱的弹窗
      keycode: '', //验证码
      Email: '', //邮箱
      numberSort: 60, //计时器
      startSet: false, //控制按钮的文字
      CopyQQ: ''
    }
  }
  static contextType = StudentInfo
  iTimer = () => {
    //计时器
    this.timer = setInterval(async () => {
      this.setState({ numberSort: this.state.numberSort - 1 })
      if (this.state.numberSort < 1) {
        clearInterval(this.timer)
        this.setState({ startSet: false, numberSort: 60 })
      }
    }, 1000)
  }
  componentDidUpdate() {
    if (this.state.numberSort < 1) {
    }
  }

  componentDidMount() {
    this.setState({
      userInfo: this.context.studentInfo,
      fileList: [
        {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: BaseUrl + this.context.studentInfo.headPicUrl
        }
      ],
      classInfo: this.context.studentInfo.classInfo || null
    })
    if (this.state.numberSort < 1) {
      this.setState({ startSet: false })
    }
  }
  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj)
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle:
        file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
    })
  }

  handleChange = ({ fileList }) => {this.setState({ fileList })}

  cancel = () => {
    this.getInfo()
    this.setState({
      editing: false
    })
  }
  gotoEdit = () => {
    this.setState({
      editing: true
    })
    getSchoollist().then((res) => {
      console.log(res.data.data[0])
      this.setState(
        {
          schoolList: res.data.data
        },
        () => {
          if (this.state.schoolId) {
            this.chooseSchool(this.state.schoolId)
          }
        }
      )
    })
  }
  chooseSchool(value) {
    let { schoolList,userInfo } = this.state
    let data = { schoolId: value }
    getClasslist(data).then((res) => {
      userInfo.schoolName = schoolList.filter((item) => item.schoolId == value)[0]
      ?.schoolName
      userInfo.schoolId = value
      this.setState({
        classList: res.data.data,
        userInfo
      })
    })
  }

  getCode = () => {
    const { CopyQQ } = this.state
    if (!CopyQQ) {
      message.error('邮箱账号不能为空！')
      return
    }
    sendCode({ QQnumber: CopyQQ }).then((res) => {
      console.log(res, '2222')
      if (res.data.code == 200) {
        this.setState({ startSet: true })
        this.iTimer()
      }
    })
  }
  chooseClass(value) {
    let { classList,userInfo } = this.state
    userInfo.classId = value
    userInfo.className = classList.filter((item) => item.classId == value)[0]?.className
    this.setState({
      userInfo
    })
  }
  onSearch = (value) => {
    console.log(value)
  }

  /* 保存 */
  submit = () => {
    const {
      fileList,
      firstChoose,
      classInfo,
    } = this.state
    const {realName, nickName, classId, schoolId, headPicUrl, schoolName, className, level} = this.state.userInfo
    let data = {
      headPicUrl: fileList[0]?.response || headPicUrl,
      nickName,
      classId,
      schoolId,
      firstChoose: firstChoose ? 1 : 0,
      realName: realName || ''
    }
    if (classInfo && level >= 10) data.corpCellName = classInfo.corpCellName
    if (!classId) {
      message.error('首次修改请选择班级')
      return
    } else if (!schoolId) {
      message.error('首次修改请选择学校')
      return
    } else {
      setMyBasicInfo(data).then((res) => {
        if (res.data?.code === 200) {
          if (firstChoose) {
            message.success('请重新登录哦～')
            this.props.history.push('/')
          } else {
            message.success('保存成功')
            this.setState({
              editing: false
            })
            this.context.getStudentInfo()
          }
        }
      })
    }
  }
  changeModal = () => {
    //
    if (this.state.userInfo?.QQnumber) {
      this.setState({
        isOpen: true,
        CopyQQ: this.state.userInfo.QQnumber
      })
    } else {
      this.setState({
        isOpen: true,
        isButton: true
      })
    }
  }
  nextStep = () => {
    //验证

    verifyEmail({
      verification: this.state.keycode,
      QQnumber: this.state.CopyQQ
    }).then((res) => {
      console.log(res.data.code, '验证消息')
      // this.setState({isButton:true});
      if (res.data.code == 200) {
        clearInterval(this.timer)
        this.setState({
          isButton: true,
          keycode: '',
          QQnumber: '',
          CopyQQ: '',
          startSet: false,
          numberSort: 60
        })
        message.success('验证成功！')
      } else if (res.data.code == 400) {
        message.error('验证码错误！')
      }
    })
  }
  FixBind = () => {
    //绑定
    if (this.state.keycode == '' || this.state.Email == '') {
      message.error('请输入完整内容！')
    } else {
      bindEmail({
        verification: this.state.keycode,
        QQnumber: this.state.Email
      }).then((res) => {
        console.log(res, '验证消息')
        if (res.data.code == 200) {
          this.setState({
            isButton: false,
            isOpen: false,
            Email: '',
            keycode: '',
            startSet: false
          })
          this.context.getStudentInfo()
          message.success('绑定成功！')
        } else {
          message.error(res.data.message)
        }
      })
    }
  }

  render() {
    const {
      userInfo,
      editing,
      schoolList,
      classList,
      previewVisible,
      previewImage,
      fileList,
      firstChoose,
      classInfo,
    } = this.state
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>上传头像</div>
      </div>
    )

    return (
      <div
        className="setinfo-all-box"
        style={{ width: '80vw', background: 'rgba(255,255,255,.4)' }}
      >
        {editing && (
          <div>
            <Button className="button-float-1" onClick={this.cancel.bind(this)}>
              取消
            </Button>
            <Button className="button-float-2" onClick={this.submit.bind(this)}>
              保存
            </Button>
          </div>
        )}
        {!editing && (
          <div>
            <Button
              className="button-float-1"
              onClick={this.gotoEdit.bind(this)}
            >
              编辑
            </Button>
          </div>
        )}
        <div style={{ padding: '0 20px' }}>
          <div className="change-box">
            <div style={{ height: '12vh' }}></div>
            <div className="flex">
              头&emsp;像：
              {!editing && userInfo?.headPicUrl &&(
                <img
                  src={BaseUrl +userInfo?.headPicUrl}
                  alt=""
                  style={{
                    width: 64,
                    height: 64,
                    borderRadius: '50%',
                    border: 'none'
                  }}
                />
              )}
              {editing && (
                <span>
                  <Upload
                    action="https://www.donglongdong.xyz/fileUpload"
                    data={{ useMethod: '上传头像', studentId: userInfo?.studentId }}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                  >
                    {fileList.length >= 1 ? null : uploadButton}
                  </Upload>
                  <Modal
                    visible={previewVisible}
                    title="预览头像"
                    footer={null}
                    onCancel={this.handleCancel}
                  >
                    <img
                      alt="example"
                      style={{ width: '100%' }}
                      src={previewImage}
                    />
                  </Modal>
                </span>
              )}
            </div>
            <div>
              昵&emsp;称：
              {!editing && <span> {userInfo?.nickName} </span>}
              {editing && (
                <Input
                  value={userInfo?.nickName}
                  onChange={(e) => {
                    userInfo.nickName = e.target.value
                    this.setState({ userInfo })
                  }}
                  style={{ width: '40%' }}
                />
              )}
            </div>
            <div>
              实&emsp;名：
              {!editing && <span> {userInfo?.realName || '暂未实名'} </span>}
              {editing && (
                <Input
                  value={userInfo?.realName}
                  disabled={!firstChoose}
                  onChange={(e) => {
                    userInfo.realName = e.target.value
                    this.setState({ userInfo })
                  }}
                  style={{ width: '40%' }}
                />
              )}
            </div>
            <div>
              QQ邮箱：
              <span style={{ marginRight: 18 }}>
                {' '}
                {userInfo?.QQnumber+'@qq.com' || '未绑定QQ'}{' '}
              </span>
              <Button
                onClick={() => {
                  this.changeModal()
                }}
                ghost
              >
                <span className="QQButton">
                  {userInfo?.QQnumber ? '修改QQ邮箱' : '绑定QQ邮箱'}
                </span>
              </Button>
            </div>
            {this.state.isOpen ? (
              <Modal
                title={this.state.isButton ? '绑定QQ邮箱' : '原邮箱验证'}
                //   centered={true}
                cancelText="取消"
                width={600}
                destroyOnClose={true}
                afterClose={() => {
                  this.setState({
                    startSet: false,
                    numberSort: 60
                  })
                }}
                okText={this.state.isButton ? '绑定' : '验证'}
                visible={this.state.isOpen}
                onOk={() => {
                  if (this.state.isButton) {
                    this.FixBind()
                  } else {
                    this.nextStep()
                  }
                }}
                onCancel={() => {
                  this.setState({
                    isOpen: false,
                    isButton: false,
                    Email: '',
                    keycode: ''
                  })
                }}
              >
                {' '}
                <div>
                  <div style={{ display: 'flex' }}>
                    <span style={{ height: '30px', lineHeight: '30px' }}>
                      {' '}
                      QQ邮箱：
                    </span>
                    <div style={{ width: '300px', height: '40px' }}>
                      <Input
                        type="text"
                        value={
                          this.state.CopyQQ
                            ? this.state.CopyQQ
                            : this.state.Email
                        }
                        onChange={(e) => {
                          this.setState({
                            CopyQQ: e.target.value,
                            Email: e.target.value
                          })
                        }}
                        width="150px"
                        placeholder="请输入邮箱"
                        disabled={this.state.isButton ? false : true}
                      />
                    </div>
                    <span style={{ height: '30px', lineHeight: '30px' }}>
                      {' '}
                      @qq.com
                    </span>
                    <Button
                      style={{ marginLeft: '10px', width: '100px' }}
                      type="primary"
                      disabled={this.state.startSet}
                      onClick={this.getCode.bind(this)}
                    >
                      {this.state.startSet
                        ? this.state.numberSort + 's'
                        : '发送验证码'}
                    </Button>
                  </div>
                  <div style={{ display: 'flex' }}>
                    <span
                      style={{
                        height: '30px',
                        marginRight: '7px',
                        lineHeight: '30px'
                      }}
                    >
                      {' '}
                      验证码：
                    </span>
                    <div style={{ width: '300px', height: '40px' }}>
                      <Input
                        type="text"
                        value={this.state.keycode}
                        onChange={(e) => {
                          this.setState({ keycode: e.target.value })
                        }}
                        placeholder="请输入六位数验证码"
                      />
                    </div>
                  </div>
                  {this.state.startSet ? (
                    <Alert
                      message={`我们已向您的邮箱 ${
                        this.state.CopyQQ ? this.state.CopyQQ : this.state.Email
                      }@qq.com发送了一封验证邮件，请核验验证码~`}
                      type="success"
                      showIcon
                    />
                  ) : (
                    ''
                  )}
                </div>
              </Modal>
            ) : (
              ''
            )}
            <div>
              学&emsp;校：
              {!editing && (
                <span>{userInfo?.schoolName === null ? '暂未选择学校' : userInfo?.schoolName}</span>
              )}
              {editing && (
                <Select
                  showSearch
                  placeholder={userInfo?.schoolName ? userInfo?.schoolName : '请选择学校'}
                  disabled={!firstChoose}
                  optionFilterProp="children"
                  onChange={this.chooseSchool.bind(this)}
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  style={{ width: '60%' }}
                >
                  {schoolList?.map((item, index) => {
                    return (
                      <Option value={item.schoolId}>{item.schoolName}</Option>
                    )
                  })}
                </Select>
              )}
            </div>
            <div>
              班&emsp;级：
              {!editing && (
                <span>{userInfo?.className === null ? '暂未选择班级' : userInfo?.className}</span>
              )}
              {editing && (
                <Select
                  showSearch
                  disabled={
                    firstChoose ? (userInfo?.schoolId === null ? true : false) : true
                  }
                  placeholder={userInfo?.className === null ? '请先选择学校' : userInfo?.className}
                  optionFilterProp="children"
                  onChange={this.chooseClass.bind(this)}
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  style={{ width: '60%' }}
                >
                  {classList?.map((item, index) => {
                    return (
                      <Option value={item.classId}>{item.className}</Option>
                    )
                  })}
                </Select>
              )}
            </div>
            <div>
              团支部名称：
              {!editing && (
                <span>
                  {classInfo?.corpCellName === null
                    ? '暂未设置团支部名称'
                    : classInfo?.corpCellName}
                </span>
              )}
              {editing && (
                <Input
                  disabled={userInfo?.level < 10 || firstChoose}
                  value={classInfo?.corpCellName}
                  onChange={(e) => {
                    let { classInfo } = this.state
                    classInfo.corpCellName = e.target.value
                    this.setState({ classInfo })
                  }}
                  style={{ width: '60%' }}
                ></Input>
              )}
            </div>
          </div>
        </div>
      </div>
    )
  }
}
export default memo(setMybasicInfo)
